package stackdemo;

import java.util.Arrays;

public class MyStack {
    public int[] elem;
    public int usedSize;
    public static final int DEFAULT_CAPACITY = 10;

    public MyStack() {
        this.elem = new int[DEFAULT_CAPACITY];
    }
    /**
     * 压栈 入栈
     */
    public void push(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,2 * elem.length);
        }
        elem[usedSize] = val;
        usedSize++;
    }
    private boolean isFull() {
        return usedSize == elem.length;
    }
    /**
     * 出栈(删除元素)
     */
    public int pop() {
        if(isEmpty()) {
            throw new IsEmptyException("栈为空!");
        }
        int oldVal = elem[usedSize - 1];
        usedSize--;
        return oldVal;
    }
    /**
     * 出栈(不删除元素)
     */
    public int peek() {
        if(isEmpty()) {
            throw new IsEmptyException("栈为空!");
        }
        int oldVal = elem[usedSize - 1];
        return oldVal;
    }
    /**
     * 判空
     * @return
     */
    public boolean isEmpty() {
        return usedSize == 0;
    }

}
